package com.yanx.system.base.query;

import com.querydsl.core.types.Projections;
import com.querydsl.core.types.QBean;
import com.yanx.common.command.Executor;
import com.yanx.common.core.command.QryCommand;
import com.yanx.common.exception.BusinessException;
import com.yanx.system.base.domain.entity.QSysDept;
import com.yanx.system.base.model.vo.SysDeptVo;
import lombok.AllArgsConstructor;

/**
 * 根据ID查询部门
 *
 * @author: gotanks
 * @create: 2023-4-12
 */
@AllArgsConstructor
public class SysDeptByIdQry extends QryCommand<SysDeptVo> {

    private Long id;

    @Override
    public SysDeptVo execute(Executor executor) {
        if (id == null) {
            throw new BusinessException("部门ID不能为空");
        }
        QSysDept sysDept = QSysDept.sysDept;
        SysDeptVo sysDeptVo = queryFactory.select(this.fields())
                .from(sysDept)
                .where(sysDept.deleted.eq(false), sysDept.id.eq(id))
                .fetchOne();
        //查询父级部门
        String parentName = queryFactory.select(sysDept.deptName)
                .from(sysDept)
                .where(sysDept.deleted.eq(false), sysDept.id.eq(sysDeptVo.getParentId()))
                .fetchOne();
        sysDeptVo.setParentName(parentName);
        return sysDeptVo;
    }

    /**
     * 部门VO映射
     *
     * @return QBean<SysDeptVo>
     */
    public static QBean<SysDeptVo> fields() {
        QSysDept sysDept = QSysDept.sysDept;
        return Projections.fields(
                SysDeptVo.class,
                sysDept.deptName,
                sysDept.orderNum,
                sysDept.leader,
                sysDept.phone,
                sysDept.email,
                sysDept.status,
                sysDept.ancestors,
                sysDept.parentId,
                sysDept.createTime,
                sysDept.id
        );
    }
}